<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Service\Dao;

use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Model\User;
use HyperfX\Utils\Service;

class UserDao extends Service
{
    public function first(int $id, $throw = false): ?User
    {
        $user = User::query()->find($id);
        if (empty($user) && $throw) {
            throw new BusinessException(ErrorCode::USER_NOT_EXISTS);
        }
        return $user;
    }

    public function firstCache(int $id, $throw = false): ?User
    {
        $user = User::findFromCache($id);
        if (empty($user) && $throw) {
            throw new BusinessException(ErrorCode::USER_NOT_EXISTS);
        }
        return $user;
    }

    public function create(string $mobile, int $type): User
    {
        $user = new User();
        $user->mobile = $mobile;
        $user->type = $type;
        $user->save();
        return $user;
    }

    public function firstByMobile(string $mobile): ?User
    {
        return User::query()->where('mobile', $mobile)->first();
    }
}
